package com.ld.controller;

import com.ld.dao.UserDao;
import com.ld.entity.Country;
import com.ld.entity.Customer;
import com.ld.entity.Staff;
import com.ld.entity.UserFile;
import com.ld.realm.StaffToken;
import com.ld.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;

@Controller
@RequestMapping("/userController")
public class UserController {

    @Resource(name = "userService")
    private UserService userService;
    @Resource(name = "userDao")
    private UserDao userDao;
    /**
     * @param userName   账号
     * @param passWord   密码
     * @param userRating  员工staff
     * @return 登录成功返回true 否则返回false
     */
    @PostMapping("/login")
    @ResponseBody
    public String login(@RequestParam("userName") String userName,
                        @RequestParam("pwd") String passWord,
                        @RequestParam("userRating") String userRating) {
        try {
            Subject subject = SecurityUtils.getSubject();
            StaffToken token = new StaffToken();
            token.setUsername(userName);
            token.setPassword(passWord.toCharArray());//将字符串转换为字符数组(setPassword只能接收字符数组)
            token.setRoleType(userRating.toUpperCase());//英文 customer 或 staff大写
            subject.login(token);
            if (subject.isAuthenticated()) {
                Session session = subject.getSession();
                Staff loginUser = (Staff) session.getAttribute("loginUser");
                loginUser.setPassWord(null);
                loginUser.setSalt(null);
                session.setAttribute("loginUser", loginUser);
                session.setAttribute("loginUserName", loginUser.getUserName());
                session.setAttribute("loginUserRating", loginUser.getRoleName().get(0));
               //通过认证,再去查头像 通过账号userName
                UserFile userFile = userDao.hasHeadPhoto(userName);
                if (userFile!=null){ //此用户有头像
                    //  loginUser.getPhotoPath()== /位置/
                    //  loginUser.getPhotoNewName() == xxxxxx.jpg
                    //前端只需加上 http://localhost:8888/项目名/位置/xxxxxx.jpg 即可访问
                    session.setAttribute("loginUserPhoto",userFile.getPath()+userFile.getNewName());
                }
            }


        } catch (UnknownAccountException e) {
            return "账号错误";
        } catch (IncorrectCredentialsException e) {
            return "密码错误";
        } catch (Exception e) {
            e.printStackTrace();
            return "未知错误";
        }
        return "success";//登录成功
    }

    /**
     * @return 退出登录
     */
    @RequestMapping("/loginOut")
    public String loginOut() {
        SecurityUtils.getSubject().logout();
        return "redirect:/"; //退出重定向
    }

    /**
     * 修改密码
     *
     * @param userName  账号
     * @param oldPwd    原始密码
     * @param newPwd    新密码
     * @param affirmPwd 确认密码
     * @return 成功与否的信息
     */
    @PostMapping("/changePwd")
    @ResponseBody
    public String changePwd(@RequestParam("userName") String userName,
                            @RequestParam("oldPwd") String oldPwd,
                            @RequestParam("newPwd") String newPwd,
                            @RequestParam("affirmPwd") String affirmPwd) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            String msg = userService.changePwd(userName, oldPwd, newPwd);
            if ("success".equals(msg)) {
                SecurityUtils.getSubject().logout();
            }
            return msg;
        }
        return "请先登录";
    }


    /**
     * @param staffId 员工id
     * @return 返回该员工的详细, 不应包括(密码, 盐, 权限)
     */
    @PostMapping(value = "/getStaffInfoByStaffId")
    @ResponseBody
    public Staff getStaffInfoByStaffId(@RequestParam("staffId") Integer staffId) {
        return userService.getStaffInfoByStaffId(staffId);
    }

    /**
     * @param userName 员工账号
     * @return 返回该员工的详细, 不应包括(密码, 盐, 权限)
     */
    @PostMapping(value = "/getStaffInfoByStaffUserName")
    @ResponseBody
    public Staff getStaffInfoByStaffUserName(@RequestParam("userName") String userName) {
        return userService.getStaffInfoByStaffUserName(userName);
    }


    /**
     * @param customerId 顾客id
     * @return 返回该顾客的详细信息
     */
    @PostMapping("/getCustomerInfoByCustomerId")
    @ResponseBody
    public Customer getCustomerInfoByCustomerId(@RequestParam("customerId") Integer customerId) {
        return userService.getCustomerInfoByCustomerId(customerId);
    }

    /**
     * @return 查询所有国家, 每个国家对应多个城市
     */
    @PostMapping("/getAllCountryAndCity")
    @ResponseBody
    public List<Country> getAllCountryAndCity() {
        return userService.getAllCountryAndCity();
    }


    /**修改员工信息
     * @param staff 员工信息
     * @return 修改成功与否的信息
     */
    @PostMapping("/changeStaffInfo")
    @ResponseBody
    public String changeStaffInfo(Staff staff) {
        return  userService.changeStaffInfo(staff);
        //return "测试";
    }

    /**
     * @param photo 上传头像图片文件
     * @return 重定向
     * @throws IOException
     */
    @PostMapping("/uploadHeadPhoto")
    public String uploadHeadPhoto(@RequestParam("uploadInput") MultipartFile photo) {

        Session session = SecurityUtils.getSubject().getSession();
        String userName = (String) session.getAttribute("loginUserName");//账号
        String msg = userService.uploadHeadPhoto(photo, userName);
        System.out.println(msg);
        return "redirect:/account/uploadheadphoto";
    }


    @RequestMapping("/aaa")
    public void name(HttpServletRequest request) throws FileNotFoundException {
       // String realPath = ResourceUtils.getURL("classpath:").getPath();
      //输出 /D:/IdeaProjects/SpringBoot/mysql_sakila/target/classes/
       // System.out.println("realPath=="+realPath);

        String realPath = ResourceUtils.getURL("user_files").getPath();
        File file =new File(realPath);
        File[] files = file.listFiles();
        for (File f : files) {
            System.out.println(f.getName());
        }
        System.out.println(realPath);
    }

}
